//
//  Ugc_ReleaseFailure_OnePicCell_WX.m
//  ZITHER
//
//  Created by weixin on 2018/9/29.
//  Copyright © 2018年 weixn. All rights reserved.
//

#import "Ugc_ReleaseFailure_OnePicCell_WX.h"
#import "NetworkEngine+imageCloudManager.h"
#import "Ugc_ReleaseFailure_VC.h"


typedef void(^AskImageUploadBlock)(BOOL isSuccess, NSString *imageURLs);

@implementation Ugc_ReleaseFailure_OnePicCell_WX


- (void)awakeFromNib {
    [super awakeFromNib];
    [self setUI];
    [self setMasonry];
    self.userInteractionEnabled = YES;
    
}


-(void)setModel:(UgcReleaseFailureModel *)model
{
    _model = model;
    
    self.usercomment.text = model.content;
    self.PicView.image = self.model.arrMPic.firstObject;

    [self layoutIfNeeded];
}



-(void)setMasonry{


    [self.usercomment mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self).offset(0);
        make.left.equalTo(self).offset(14);
        make.right.equalTo(self).offset(-14);
    }];
    
    
    [self.userPic mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.usercomment.mas_bottom).offset(10);
        make.left.equalTo(self).offset(14);
        make.right.equalTo(self).offset(-14);
        make.height.mas_equalTo((kScreenW-28)/3.0*2);
    }];
    
    [self.PicView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.usercomment.mas_bottom).offset(10);
        make.left.equalTo(self).offset(14);
        make.right.equalTo(self).offset(-14);
        make.height.mas_equalTo((kScreenW-28)/3.0*2);
    }];
    
    
    [self.resend mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.userPic.mas_bottom).offset(20);
        make.left.equalTo(self.del.mas_right).offset(50);
    }];
    
    [self.del mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.userPic.mas_bottom).offset(20);
        make.left.equalTo(self).offset(14);
    }];
    
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 1, 1)];
    view.backgroundColor = [UIColor colorWithHex:@"EEEEEE"];
    [self addSubview:view];
    [view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.del.mas_bottom).offset(25);
        make.left.right.equalTo(self).offset(0);
        make.height.mas_equalTo(1);
        make.bottom.equalTo(self).offset(-26);
    }];
}


-(void)setUI{
    [self addSubview:self.resend];
    [self addSubview:self.del];
    [self addSubview:self.usercomment];
    [self addSubview:self.userPic];
    [self.userPic addSubview:self.PicView];
}

-(QMUILabel *)usercomment{
    if (!_usercomment) {
        _usercomment = [[QMUILabel alloc]initWithFrame:CGRectMake(0, 0, 1, 1)];
        _usercomment.numberOfLines = 0;
        _usercomment.font = [UIFont systemFontOfSize:18];
    }
    return _usercomment;
}

-(UIView *)userPic{
    if (!_userPic) {
        _userPic = [[QMUILabel alloc]initWithFrame:CGRectMake(0, 0, 1, 1)];
        _userPic.userInteractionEnabled = YES;
        
    }
    return _userPic;
}

-(UIImageView *)PicView{
    if (!_PicView) {
        _PicView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 1, 1)];
        [_PicView setCornerRadiusWithRadius:8 isMasks:YES];
        _PicView.contentMode = 2;
        _PicView.tag = 100;
        _PicView.backgroundColor = [UIColor randomColor];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] init];
        [[tap rac_gestureSignal] subscribeNext:^(__kindof UIGestureRecognizer * _Nullable x) {
//            [self showBigImage:100];
        }];
        [_PicView addGestureRecognizer:tap];
        _PicView.userInteractionEnabled = NO;
    }
    return _PicView;
}
//
//-(void)showBigImage:(NSInteger)selectIndex{
//    UIImageView *imageV = [self.userPic viewWithTag:selectIndex];
//    // self.model.fileList[selectIndex-100];
//
//    if (!self.imagePreviewViewController) {
//        self.imagePreviewViewController = [[QMUIImagePreviewViewController alloc] init];
//        self.imagePreviewViewController.imagePreviewView.delegate = self;
//
//        // QMUIImagePreviewViewController 对于以 window 的方式展示的情况，默认会开启手势拖拽退出预览功能。
//        // 如果使用了手势拖拽，并且退出预览时需要飞到某个 rect，则需要实现这个 block，在里面自己去 exit，如果不实现这个 block，退出动画会使用 fadeOut 那种
//
//    }
//    __weak __typeof(self)weakSelf = self;
//    self.imagePreviewViewController.customGestureExitBlock = ^(QMUIImagePreviewViewController *aImagePreviewViewController, QMUIZoomImageView *currentZoomImageView) {
//        NSInteger index = aImagePreviewViewController.imagePreviewView.currentImageIndex;
//        UIImageView *imageV1 = [weakSelf.userPic viewWithTag:index+100];
//
//        //        imageV.image = currentZoomImageView.image;
//        //            [weakSelf.imageButton setImage:currentZoomImageView.image forState:UIControlStateNormal];
//
//        [aImagePreviewViewController exitPreviewToRectInScreenCoordinate:[imageV1 convertRect:imageV1.frame toView:nil]];
//
//    };
//    self.imagePreviewViewController.imagePreviewView.currentImageIndex =  selectIndex-100;// 默认查看的图片的 index
//
//    [self.imagePreviewViewController startPreviewFromRectInScreenCoordinate:[imageV convertRect:imageV.frame toView:nil] cornerRadius:imageV.layer.cornerRadius];
//}
//
//
//#pragma mark - <QMUIImagePreviewViewDelegate>
//
//- (NSUInteger)numberOfImagesInImagePreviewView:(QMUIImagePreviewView *)imagePreviewView {
//    return self.model.fileList.count;
//}
//
//- (void)imagePreviewView:(QMUIImagePreviewView *)imagePreviewView renderZoomImageView:(QMUIZoomImageView *)zoomImageView atIndex:(NSUInteger)index {
//    // 模拟异步加载的情况
//    zoomImageView.reusedIdentifier = @(index);
//    [zoomImageView showLoading];
//    if ([zoomImageView.reusedIdentifier isEqual:@(index)]) {
//        [zoomImageView hideEmptyView];
//        UIImageView *imageV = [self.userPic viewWithTag:100+index];
//        zoomImageView.image = imageV.image;
//
//    }
//    //    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//    //
//    //    });
//}
//
//- (QMUIImagePreviewMediaType)imagePreviewView:(QMUIImagePreviewView *)imagePreviewView assetTypeAtIndex:(NSUInteger)index {
//    return QMUIImagePreviewMediaTypeImage;
//}
//
//#pragma mark - <QMUIZoomImageViewDelegate>
//
//- (void)singleTouchInZoomingImageView:(QMUIZoomImageView *)zoomImageView location:(CGPoint)location {
//    //点击缩回
//    self.imagePreviewViewController.customGestureExitBlock(self.imagePreviewViewController, zoomImageView);
//}
//

-(QMUIButton *)resend{
    if (!_resend) {
        _resend = [[QMUIButton alloc]initWithFrame:CGRectMake(0, 0, 1, 1)];
        [_resend setTitle:@"重新发送" forState:UIControlStateNormal];
        [_resend setTitleColor:baseColorTheme forState:UIControlStateNormal];
        [_resend setCornerRadiusWithRadius:10 isMasks:YES];
        //        [_resend setBorderWithColor:[UIColor blackColor] width:1];
        
        @weakify(self);
        [[_resend rac_signalForControlEvents:(UIControlEventTouchUpInside)] subscribeNext:^(__kindof UIControl * _Nullable x) {
            @strongify(self);
            [self send];
        }];
    }
    return _resend;
}

-(QMUIButton *)del{
    if (!_del) {
        _del = [[QMUIButton alloc]initWithFrame:CGRectMake(0, 0, 1, 1)];
        [_del setTitle:@"删除" forState:UIControlStateNormal];
        [_del setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        //        _del.backgroundColor = [UIColor redColor];
        [_del setCornerRadiusWithRadius:10 isMasks:YES];
        @weakify(self);
        [[_del rac_signalForControlEvents:(UIControlEventTouchUpInside)] subscribeNext:^(__kindof UIControl * _Nullable x) {
            @strongify(self);
            [kUSER_INFO_MANAGER delFailureModel:self.indexPath.row];
            [Tools showTips:@"删除成功"];
            
            Ugc_ReleaseFailure_VC *vc = (Ugc_ReleaseFailure_VC*)[self getViewController:[Ugc_ReleaseFailure_VC class]];
            
            [vc.tbv removeCell:self];
//            if (self.block) {
//                self.block();
//            }
        }];
    }
    return _del;
}



-(void)send{
    
    //是否有图片
    if (self.model.arrMPic.count > 0) {
        //有图片  先上传图片
        
        [self uploadImageWithPhotos:self.model.arrMPic.copy completion:^(BOOL isSuccess, NSString *imageURLs) {
            if (isSuccess) {
                [Tools showTips:@"发送成功"];
                
                [kUSER_INFO_MANAGER delFailureModel:self.indexPath.row];
                Ugc_ReleaseFailure_VC *vc = (Ugc_ReleaseFailure_VC*)[self getViewController:[Ugc_ReleaseFailure_VC class]];
                
                [vc.tbv removeCell:self];
//                if (self.block) {
//                    self.block();
//                }
            } else {
                [Tools showTips:@"发送失败"];
            }
        }];
    }else{
        //没图片
        [[serviceDefualt loadGetAddUserUgc:self.model.content fileList:nil userSubjectId:self.model.topicID reponseObjctClass:nil]subscribeNext:^(ResponseData * x) {

//        [[serviceDefualt loadGetAddUserUgc:self.model.content fileList:nil reponseObjctClass:nil]subscribeNext:^(ResponseData * x) {
            
            if (x.success) {
                [Tools showTips:@"发送成功"];
                
                [kUSER_INFO_MANAGER delFailureModel:self.indexPath.row];
                Ugc_ReleaseFailure_VC *vc = (Ugc_ReleaseFailure_VC*)[self getViewController:[Ugc_ReleaseFailure_VC class]];
                
                [vc.tbv removeCell:self];
//                if (self.block) {
//                    self.block();
//                }
            }else{
                [Tools showTips:@"发送失败"];
            }
        }];
    }
}

#pragma mark - 上传图片
- (void)uploadImageWithPhotos:(NSArray<UIImage *> *)photos completion:(AskImageUploadBlock)completion {
    //  开启菊花
    [QMUITips showLoadingInView:self];
    // 调度组
    dispatch_group_t group = dispatch_group_create();
    // 队列
    dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
    __block NSMutableArray<NSString *> *uploadURLs = @[].mutableCopy;
    for (NSUInteger i = 0; i< photos.count; i++) {
        UIImage *image = [photos objectAtIndex:i];
        //分别开组
        dispatch_group_enter(group);
        dispatch_group_async(group, queue, ^{
            NSString *date = [NSString currentDateDateFormatter:@"yyyyMM"];
            NSString *path =[NSString stringWithFormat:@"/ugc/%@",date];
            
            [kNetworkShared getImageURLWithImageOld:image Path:path batchIndex:i completion:^(COSObjectUploadTaskRsp *uploadTaskRsp, NSString *filePath, NSString *fileName, BOOL isSuccess, NSError *error) {
                if (isSuccess) {
                    [uploadURLs addObject:kSTRING_FORMAT(@"%@/%@",filePath, fileName)];
                }
                dispatch_group_leave(group);
            }];
            
        });
    }
    //完成通知
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        [QMUITips hideAllTipsInView:self];
        if (uploadURLs.count == photos.count) {
            NSString *imgURLs = [uploadURLs componentsJoinedByString:@","];
            // 全部上传成功
            [[serviceDefualt loadGetAddUserUgc:self.model.content fileList:uploadURLs userSubjectId:self.model.topicID reponseObjctClass:nil]subscribeNext:^(ResponseData * x) {

                if (x.success) {
                    if (completion) {
                        completion(YES, imgURLs);
                    }
                }else{
                    if (completion) {
                        completion(NO, nil);
                    }
                }
            }];
            
        } else {
            if (completion) {
                completion(NO, nil);
            }
        }
    });
}
@end

